#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test, login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse

from osmp.host.models import Host, Product, Host2Pro
from osmp.monitor.models import Monitor,Alert,AlertReceive
from osmp.util import commom

import time,datetime,json
import settings

@login_required
def alertlist(request):
    auth_pids = request.session['auth_pids']
    tree = ""  
    tree = commom.creatree(-1, tree, '', '/monitor/monitorlist?id=', auth_pids = auth_pids)

    try:
        id = request.GET.get('id','-1')
        merge = request.GET.get('merge', 'on')
        page = int(request.GET.get("page",1))
        lastweek = datetime.datetime.today() - datetime.timedelta(days=7)
        if id == '-1':
            alerts = Alert.objects.select_related(depth=1).filter(
                    mid__pid__in = request.session['auth_pids'], 
                    timestamp__gte =    lastweek).order_by('-timestamp')
        else:
            alerts = Alert.objects.select_related(depth=1).filter(
                    mid = id, timestamp__gte = lastweek).order_by('-timestamp')
    except:
        raise

    if merge == 'on':
        uniqAlert = []
        uniqKey= {}
        for elem in alerts:
            mid = str(elem.mid.id)
            if uniqKey.has_key(mid):
                uniqKey[mid] += 1
            else:
                uniqKey[mid] = 1
                uniqAlert.append(elem)
        for elem in uniqAlert:
            mid = str(elem.mid.id)
            elem.num = uniqKey[mid]
    else:
        uniqAlert = alerts

    return render_to_response("alert.html",locals())

@login_required
def replay(request, id):
    id = int(id)
    alt = Alert.objects.get(id = id)
    if request.method == "POST":
        reason = request.POST.get('reason')
        rtype = request.POST.get('rtype')
        alt.reason = reason
        alt.rtype = rtype
        alt.uid = request.user.username
        alt.save()
        return HttpResponseRedirect('/alert/reason/%d/' % id)
    else:
        return render_to_response('alertreplay.html', locals())
 

@login_required
def reason(request, id):
    id = int(id)
    alt = Alert.objects.get(id = id)
    return render_to_response('alertreason.html', locals())


@login_required
def search(request):
    if request.method == 'POST':
        start = request.POST.get('start')
        end = request.POST.get('end')
        merge = request.POST.get('merge', 'off')
        notreplay = request.POST.get('notreplay', 'off')

        print "====", notreplay

    auth_pids = request.session['auth_pids']
    tree = ""  
    tree = commom.creatree(-1, tree, '', '/monitor/monitorlist?id=', auth_pids = auth_pids)

    try:
        lastweek = datetime.datetime.today() - datetime.timedelta(days=7)
        if id == '-1':
            if notreplay == 'on':
                alerts = Alert.objects.select_related(depth=1).filter(
                    mid__pid__in = request.session['auth_pids'], 
                    timestamp__gte =    start + " 00:00:00",
                    timestamp__lte = end + " 23:59:59",
                    rtype = "",
                    ).order_by('-timestamp')
            else:
                alerts = Alert.objects.select_related(depth=1).filter(
                    mid__pid__in = request.session['auth_pids'], 
                    timestamp__gte =    start + " 00:00:00",
                    timestamp__lte = end + " 23:59:59",
                    ).order_by('-timestamp')


        else:
            if notreplay == 'on':
                alerts = Alert.objects.select_related(depth=1).filter(
                    mid__pid__in = request.session['auth_pids'], 
                    timestamp__gte =    start + " 00:00:00",
                    timestamp__lte = end + " 23:59:59",
                    rtype = "",
                    ).order_by('-timestamp')
            else:
                alerts = Alert.objects.select_related(depth=1).filter(
                    mid__pid__in = request.session['auth_pids'], 
                    timestamp__gte =    start + " 00:00:00",
                    timestamp__lte = end + " 23:59:59",
                    ).order_by('-timestamp')
    except:
        raise

    if merge == 'on':
        uniqAlert = []
        uniqKey= {}
        for elem in alerts:
            mid = str(elem.mid.id)
            if uniqKey.has_key(mid):
                uniqKey[mid] += 1
            else:
                uniqKey[mid] = 1
                uniqAlert.append(elem)
        for elem in uniqAlert:
            mid = str(elem.mid.id)
            elem.num = uniqKey[mid]
    else:
        uniqAlert = alerts

    return render_to_response("alert.html",locals())



@login_required
def searcht(request):
    errors = []
    message = []
    if not request.POST.get('pid', ''):
        errors.append('请选择产品线')
    if errors:
        return render_to_response("alert.html",locals())
    else:
        pid = request.POST.get('pid')
        lst = Monitor.objects.filter(pid = pid)
        id = []
        if lst:
            for l in lst:
                id.append(l.id)
            alerts = Alert.objects.filter(mid__in = id)
            flag="open"
        else:
            message.append("该产品线无报警数据")
    plist = request.session.get('plist')
    request.session['alerts'] = alerts
    return render_to_response("alert.html",locals())

#CSV的导出
import csv
def export(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(mimetype='text/csv')
    response.write('\xEF\xBB\xBF')
    tim = str(long(time.time()*1000))
    s = 'attachment; filename=Alert-%s.csv'%tim
    response['Content-Disposition'] = s
    alerts = request.session.get('alerts')
    writer = csv.writer(response)
    
    writer.writerow(['ID', u'时间'.encode('gbk'), 'URL', u'监控名称'.encode('gbk'), u'持续时间'.encode('gbk'), u'目前状态'.encode('gbk'), u'主机名称'.encode('gbk')])
#    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
    for a in alerts:
        mname = a.mid.mname.encode('gbk')
        hname = a.mid.hid.name.encode('gbk')
        writer.writerow([a.id,a.timestamp,mname,a.downtime,a.mid.status,hname])
    
    user = request.user.username
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    writer.writerow([u"用户：".encode('gbk'),user,u"操作时间：".encode('gbk'),now])
    flag = ""
    return response

def people(request):
    alert_user = User.objects.all()
    return render_to_response("alertpeople.html",locals())


def reset(request):
    uid = int(request.GET.get('id', 1))
    alert = AlertReceive.objects.filter(uid = uid)
    monitor = Monitor.objects.all()
    alert_mid = []
    for a in alert:
        alert_mid.append(a.mid.id)
    unset_monitor = []
    for m in monitor:
        if m.id in alert_mid:
            continue
        else:
            unset_monitor.append(m)
    return render_to_response("alertreset.html",locals())


def delete(request):
    id = int(request.GET.get('id', -1))
    if id == -1:
        ret = {'flag': 'false'}
    else:
        alert = AlertReceive.objects.filter(id = id)
        alert.delete()
        ret = {'flag': 'true'}
        #通知daemon端
        
    return HttpResponse(json.dumps(ret))

def ajaxAdd(request):
    mid = int(request.GET.get('mid', -1))
    uid = int(request.GET.get('uid', -1))
    if mid == -1 or uid == -1:
        ret = {'flag': 'false'}
    else:
        ar = AlertReceive.objects.create(
                mid = Monitor.objects.get(id = mid),
                uid = User.objects.get(id = uid),
                mode = "1100")
        ar.save()

        #通知daemon端(由于速度太慢，因此改掉)

        ret = {'flag': 'true'}
    return HttpResponse(json.dumps(ret))


def ajaxReplay(request):
    ret = {'flag': 'error'}
    if request.method == 'POST':
        ids = request.POST.get('ids', '')
        rtype = request.POST.get('rtype', '')
        reason = request.POST.get('reason', '')
        if not ids.strip():
            return HttpResponse(json.dumps(ret))
        objs = Alert.objects.filter(id__in = ids.split())
        for e in objs:
            e.rtype= rtype
            e.reason = reason
            e.uid = request.user.username
            e.save()
        
        ret = {'flag': 'succ'}
        return HttpResponse(json.dumps(ret))
    else:
        return HttpResponse(json.dumps(ret))

def ajaxDel(request):
    ret = {'flag': 'error'}
    if request.method == 'POST':
        ids = request.POST.get('ids', '')
        if not ids.strip():
            return HttpResponse(json.dumps(ret))
        objs = Alert.objects.filter(id__in = ids.split())
        for e in objs:
            e.delete()
        
        ret = {'flag': 'succ'}
        return HttpResponse(json.dumps(ret))
    else:
        return HttpResponse(json.dumps(ret))

